package com.amithkoujalgi.myapp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amithkoujalgi.myapp.core.AppConstants;
import com.amithkoujalgi.myapp.domain.GoogleAccessToken;
import com.amithkoujalgi.myapp.utils.GoogleURLBuilder;
import com.amithkoujalgi.myapp.utils.HTTPUtil;

@SuppressLint("SetJavaScriptEnabled")
public class LogoutActivity extends Activity {
	private static boolean loggedIn = false;

	// Change the Scope as you need
	WebView webView;
	Button googleOauthBtn;
	SharedPreferences sharedPreferences;
	TextView tokensTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sharedPreferences = getSharedPreferences("AppPref", MODE_PRIVATE);
		tokensTextView = (TextView) findViewById(R.id.access);
		googleOauthBtn = (Button) findViewById(R.id.auth);
		googleOauthBtn.setOnClickListener(new View.OnClickListener() {
			Dialog auth_dialog;

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				auth_dialog = new Dialog(LogoutActivity.this);
				auth_dialog.setContentView(R.layout.auth_dialog);
				webView = (WebView) auth_dialog.findViewById(R.id.webview);
				webView.getSettings().setJavaScriptEnabled(true);
				if (loggedIn) {
					webView.loadUrl(AppConstants.GoogleURL.OAUTH_BROWSER_LOGOUT_URL);
				} else {
					webView.loadUrl(GoogleURLBuilder.getLoginURL(
							AppConstants.OAuthScope.VIEW_USER_EMAIL,
							AppConstants.OAuthScope.VIEW_USER_PROFILE));
				}
				webView.setWebViewClient(new WebViewClient() {
					boolean authComplete = false;
					Intent resultIntent = new Intent();

					@Override
					public void onPageStarted(WebView view, String url,
							Bitmap favicon) {
						super.onPageStarted(view, url, favicon);
					}

					String authCode;

					@Override
					public void onPageFinished(WebView view, String url) {
						super.onPageFinished(view, url);

						if (url.contains("?code=") && authComplete != true) {
							Uri uri = Uri.parse(url);
							authCode = uri.getQueryParameter("code");
							Log.i("", "CODE : " + authCode);
							authComplete = true;
							resultIntent.putExtra("code", authCode);
							LogoutActivity.this.setResult(Activity.RESULT_OK,
									resultIntent);
							setResult(Activity.RESULT_CANCELED, resultIntent);
							SharedPreferences.Editor edit = sharedPreferences
									.edit();
							edit.putString("Code", authCode);
							edit.commit();
							auth_dialog.dismiss();
							new TokenGet().execute();
							// Toast.makeText(getApplicationContext(),
							// "Authorization Code is: " + authCode,
							// Toast.LENGTH_SHORT).show();
						} else if (url.contains("error=access_denied")) {
							Log.i("", "ACCESS_DENIED_HERE");
							resultIntent.putExtra("code", authCode);
							authComplete = true;
							setResult(Activity.RESULT_CANCELED, resultIntent);
							Toast.makeText(getApplicationContext(),
									"Error Occured", Toast.LENGTH_SHORT).show();
							auth_dialog.dismiss();
						} else if (url.contains("ServiceLogin")) {
							if (loggedIn) {
								Toast.makeText(getApplicationContext(),
										"Logged out", Toast.LENGTH_SHORT)
										.show();
								tokensTextView.setText("Signed out of Google.");
								loggedIn = false;
								Intent mainIntent = new Intent(
										getApplicationContext(),
										LogoutActivity.class);
								mainIntent
										.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(mainIntent);
							}
						}
					}
				});
				auth_dialog.show();
				if (!loggedIn) {
					auth_dialog.setTitle("Sign-in with Google");
				} else {
					auth_dialog.setTitle("Signing out...");
				}
				auth_dialog.setCancelable(true);
			}
		});
	}

	private class TokenGet extends AsyncTask<String, String, GoogleAccessToken> {
		private ProgressDialog pDialog;
		String Code;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LogoutActivity.this);
			pDialog.setMessage("Contacting Google ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			Code = sharedPreferences.getString("Code", "");
			pDialog.show();
		}

		@Override
		protected GoogleAccessToken doInBackground(String... args) {
			HTTPUtil http = new HTTPUtil();
			GoogleAccessToken gToken = http.getGoogleToken(
					AppConstants.TOKEN_URL, Code, AppConstants.CLIENT_ID,
					AppConstants.CLIENT_SECRET, AppConstants.REDIRECT_URI,
					AppConstants.GRANT_TYPE);
			return gToken;
		}

		@Override
		protected void onPostExecute(GoogleAccessToken googleTokens) {
			pDialog.dismiss();
			if (googleTokens != null) {
				try {
					String accessToken = googleTokens.getAccess_token();
					long expire = googleTokens.getExpires_in();
					String refresh = googleTokens.getRefresh_token();
					Log.d("Token Access", accessToken);
					Log.d("Expires in", Long.toString(expire));
					Log.d("Refresh", refresh);
					loggedIn = true;

					googleOauthBtn.setText("Sign out");
					tokensTextView.setText("Access Token:" + accessToken
							+ "nExpires:" + expire + "nRefresh Token:"
							+ refresh);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Toast.makeText(getApplicationContext(), "Network Error",
						Toast.LENGTH_SHORT).show();
				pDialog.dismiss();
			}
		}
	}
}